package com.dzf.controller;

import com.dzf.entity.*;
import com.dzf.service.CartService;

import com.dzf.service.OrdService;

import com.dzf.util.SessionUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RequestMapping("/api/fore")
@RestController
public class ForeController {
    @Autowired
    CartService cartService;
    @Autowired
    OrdService ordService;

    @Autowired
    SessionUtil sessionUtil;

    /**
     * 获取用户的购物车
     * @return 登录用户的购物车信息
     */
    @RequestMapping("/findAll")
    public RespJson findAll()
    {
        MyUser user = (MyUser)sessionUtil.getUser();
        if (user.getId()==0)
        {
            return RespJson.pack(401,"未登录！",null);
        }
        return RespJson.pack(200,"OK",cartService.findAll(user.getId()));
    }

    /**
     * 删除购物车的信息
     * @param map 购物车中的信息
     * @return 无data
     */
    @RequestMapping("/cart/deleteMyCart")
    public RespJson deleteMyCart(@RequestBody Map<String,Object> map){
        MyUser user = (MyUser) sessionUtil.getUser();
        cartService.deleteMyCart((List<Object>) map.get("bookid"),user.getId());
        return RespJson.pack(200,"添加成功",null);
    }

    /**
     * 添加购物车
     * @param cart 购物车实体类，接收加入到购物车的商品详情
     * @return 无data
     */
    @RequestMapping("/cart/addCart")
    public RespJson addCart(@RequestBody Cart cart){
        MyUser user = (MyUser) sessionUtil.getUser();
        cart.setUid(user.getId());
        cart.setTcreate(new Date());
        cart.setNum(1);
        System.err.println(cart);
        cartService.updCart(cart);
        return RespJson.pack(200,"添加成功",null);
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }
}
